import { CacheEnum } from "@/enums/CacheEnum"
import { PagesType } from "@/router/types/pages"
import { store } from '@/store'
import { getUid } from "@/tmui/tool/function/util"
import dayjs from "dayjs"

export type SearchHistoryVal = {
  id: string
  key: string
  createTime: string
  updateTime: string
  count: number
}
interface UseCurrRole {
  searchHistory: {
    [key in PagesType]?: SearchHistoryVal[]
  }
}

const createState = (): UseCurrRole => ({
  searchHistory: uni.getStorageSync(CacheEnum.SEARCH_HISTORY) || {}
})

export const useSearchHistoryStore = defineStore({
  id: 'searchHistory',
  state: () => createState(),
  actions: {
    /**
     * @description 创建一个历史记录项
     * @date 10/11/2023
     * @param {string} key
     * @returns {SearchHistoryVal}
     */
    createSearchHistoryItem(key: string): SearchHistoryVal {
      const time = dayjs(new Date()).format('YYYY/MM/DD HH:mm')
      return {
        id: getUid(),
        key,
        createTime: time,
        updateTime: time,
        count: 1
      }
    },
    /**
     * @description 设置搜索历史
     * @date 10/11/2023
     * @param {PagesType} page
     * @param {SearchHistoryVal[]} searchHistory
     */
    setSearchHistory(page: PagesType, searchHistory: SearchHistoryVal[]) {
      this.searchHistory[page] = searchHistory
      this.updateSearchHistory()
    },
    /**
     * @description 获取搜索历史
     * @date 10/11/2023
     * @param {PagesType} page
     * @returns {*}  {(SearchHistoryVal[] | void)}
     */
    getSearchHistory(page: PagesType): SearchHistoryVal[] | void {
      return this.searchHistory[page]
    },
    /**
     * @description 删除指定项搜索历史
     * @date 10/11/2023
     * @param {PagesType} page
     */
    delSearchHistory(page: PagesType) {
      this.searchHistory[page] = []
      this.updateSearchHistory()
    },
    /**
     * @description 清除所以搜索历史
     * @date 10/11/2023
     */
    clearSearchHistory() {
      this.searchHistory = {}
      this.updateSearchHistory()
    },
    /**
     * @description 更新搜索历史
     * @date 10/11/2023
     */
    updateSearchHistory() {
      uni.setStorageSync(CacheEnum.SEARCH_HISTORY, this.searchHistory)
    }
  },
})

export function useSearchHistoryStoreWithOut() {
  return useSearchHistoryStore(store);
}
